﻿using Ldt.DataEngine.DataFlowParse.Model;
using Ldt.DataEngine.RuleAssemble;
using LdtDataEngin.ModuleDetail.BaseModule;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.CommHelp;
using LdtJudge.DataEngine.Common.StringAssemble;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.DataModel.SysCommon;
using LdtJudge.DataEngine.Model.DataModel.SystemtableModel;
using LdtJudge.DataEngine.Model.ElmentModel;
using LdtJudge.DataEngine.Model.XMLConfigModel.CircumsatanModel;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using LdtJudge.DataEngine.Model.XMLConfigModel.SituationPloModel;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Xml;

namespace LdtDataEngin.ModuleDetail.AnalysisModule.SituationPlot
{
    /// <summary>
    /// 情形获取
    /// </summary>
    public class ExtSituationData : SituationPlotBaseClass
    {
        /// <summary>
        /// 模块名称
        /// </summary>
        private readonly string _moduleName;

        public string casecauseid;

        /// <summary>
        /// 获取配置信息
        /// </summary>
        public List<ParagraphModel> paragraphModelList = new List<ParagraphModel>();
        /// <summary>
        /// 模块的配置
        /// </summary>
        private CircumsatanModel circumsatanModel = new CircumsatanModel();
        /// <summary>
        /// 机器学习配置
        /// </summary>
        private SituationPlotMLConfigModel mlConfigModel = null;

        /// <summary>
        /// 匹配整句文本与节点集合
        /// </summary>
        private Dictionary<string, List<CommonPlotorSituation>> dicContent = new Dictionary<string, List<CommonPlotorSituation>>();

        /// <summary>
        /// 匹配拆句文本与节点集合
        /// </summary>
        //private Dictionary<string, List<CommonPlotorSituation>> dicFJContent = new Dictionary<string, List<CommonPlotorSituation>>();

        public ExtSituationData(DataContext dataContext, string moduleName)
        {
            _moduleName = moduleName;
            base.dataContext = dataContext;
            var configmodel = dataContext.DataLayerSys.GetConfigModel(moduleName);
            var configCode = string.Empty;
            if (moduleName.ToLower().IndexOf("ldtdataengin.moudle.moudlecasecauseelementextract") > -1)
                configCode = "causeqxextract";
            else if (moduleName.ToLower().IndexOf("ldtdataengin.moudle.moudlesituationmatch") > -1)
                configCode = "qxextract";
            if (!string.IsNullOrEmpty(configCode) && configmodel != null && configmodel.ConfigDetail != null && configmodel.ConfigDetail.Count > 0)
            {
                ConfigModel situationConfig = configmodel.ConfigDetail.FirstOrDefault(x => x.Code.ToLower() == configCode);
                circumsatanModel = XmlUtility.DeserializeToObject<CircumsatanModel>(situationConfig?.ConfigContent);
            }

            ConfigModel mlConfig = configmodel.ConfigDetail.FirstOrDefault(x => x.Code.ToLower() == "qxqjmatchlearn");
            if (mlConfig != null)
            {
                mlConfigModel = XmlUtility.DeserializeToObject<SituationPlotMLConfigModel>(mlConfig?.ConfigContent);
            }
            //// 根据模块名称获取配置并解析
            //circumsatanModel = XmlUtility.DeserializeToObject<CircumsatanModel>(dataContext.DataLayerSys.GetConfigXml(moduleName).OuterXml);
        }
        public ExtSituationData(string ConfigContent)
        {
            mlConfigModel = XmlUtility.DeserializeToObject<SituationPlotMLConfigModel>(ConfigContent);
        }
        /// <summary>
        /// 根据内容返回匹配后的情形内容对象
        /// </summary>
        /// <param name="CauseID">案由ID</param>
        /// <param name="IsDevelopSchedule">匹配状态</param>
        /// <param name="MatchText">内容</param>
        /// <param name="commElement">条件对象</param>
        /// <param name="district">地域</param>
        /// <returns></returns>
        public override List<CommonPlotorSituation> MatchValueID(string CauseID, bool IsDevelopSchedule, string MatchText, CommElementRegexCode commElement, string affirmType, string district, string isml)
        {
            List<CommonPlotorSituation> listMPlot = new List<CommonPlotorSituation>();
            if (!string.IsNullOrWhiteSpace(CauseID))
            {
                ///查询个罪下的犯罪情形
                //string sqlstr = "SELECT * FROM dbo.SYS_CaseCause WHERE AllParentId LIKE '%," + CauseID + ",%'  AND cc_nodetype = 4   ORDER BY CC_GlobalOrder";
                Stopwatch s1 = new Stopwatch();
                s1.Start();
                List<SYS_CaseCause> CommonTable = dALSYS_CaseCause.GetMatchValueIDByCauseID(CauseID, isml);
                s1.Stop();
                RuleParseClass.WriteContentLog("获取到需要匹配的节点：" + JsonConvert.SerializeObject(CommonTable) + "数量：" + CommonTable.Count + " 耗时：" + s1.ElapsedMilliseconds + "毫秒");
                System.Diagnostics.Stopwatch plotwatch = new System.Diagnostics.Stopwatch();
                plotwatch.Start();
                base.dataContext?.InteractiveShow?.LogShow("      情形匹配的原文内容为：" + MatchText);
                base.dataContext?.InteractiveShow?.LogShow("      根据当前原文进行个罪情形的匹配===开始===");
                if (IsDevelopSchedule)
                {
                    base.LoopExtractPlotCommon(CauseID, MatchText, CommonTable, CauseID, commElement, affirmType, ref listMPlot);
                }
                else
                {
                    base.LoopExtractRuleItem(CauseID, MatchText, CommonTable, CauseID, commElement, affirmType, ref listMPlot);
                }

                plotwatch.Stop();
                if (listMPlot.Count > 0)
                {
                    base.dataContext?.InteractiveShow?.LogShow("      根据原文匹配到的情形如下：");
                    for (int i = 0; i < listMPlot.Count; i++)
                    {
                        var mo = listMPlot[i];
                        base.dataContext?.InteractiveShow?.LogShow(string.Format("      匹配到的 第{0}个 情形为：名称：{1} ,节点ID为：{2}", (i + 1), mo.Common_name, mo.Common_id));
                        var content = mo.Common_originalText.Trim(new char[] { '，', '。' });
                        //if (!dicFJContent.ContainsKey(content))
                        //{
                        //    dicFJContent.Add(content, new List<CommonPlotorSituation> { mo });
                        //}
                        //else if (!dicFJContent[content].Any(x=>x.Common_id==mo.Common_id&&x.Common_name==mo.Common_name))
                        //{                           
                        //    dicFJContent[content].Add(mo);
                        //}
                    }
                }
                base.dataContext?.InteractiveShow?.LogShow("      根据当前原文进行个罪情形的匹配===结束===用时为：" + plotwatch.ElapsedMilliseconds + "毫秒");
                RuleParseClass.WriteContentLog("根据当前原文进行个罪情形的匹配===结束===用时为：" + plotwatch.ElapsedMilliseconds + "毫秒");
            }
            return listMPlot;
        }


        /// <summary>
        /// 公共能力获取情形情节
        /// </summary>
        /// <param name="paragraphCode">段落编号</param>
        /// <param name="paragraphValue">段落内容</param>
        /// <param name="caseType">案件类型</param>
        /// <param name="docType">文书类型</param>
        /// <param name="caseCauseCode">案由id</param>
        /// <param name="cofige">配置文件</param>
        /// <returns></returns>
        public List<Dictionary<string, string>> MatchSituationSupplementSuperr(string paragraphCode, string paragraphValue, string caseType, string docType, string caseCauseCode, string cofige, string moduleType)
        {
            List<Dictionary<string, string>> rowsdic = new List<Dictionary<string, string>>();
            GetSysCaseCause getSysCaseCause = new GetSysCaseCause();
            List<CaseCauseModel> caseCausesList = new List<CaseCauseModel>();
            if (!string.IsNullOrEmpty(caseCauseCode))
            {
                List<string> causeListvalue = caseCauseCode.Split(',').ToList();
                foreach (string value in causeListvalue)
                {
                    if (!string.IsNullOrWhiteSpace(value))
                    {
                        caseCausesList.Add(getSysCaseCause.GetModel(value));
                    }
                }
            }
            circumsatanModel = XmlUtility.DeserializeToObject<CircumsatanModel>(cofige);
            ParagraphModel paragraphmodel = GetConfigModel(cofige, caseType, docType, paragraphCode);
            if (paragraphmodel != null)
            {
                SituationPlotMLCaseType mlCaseType = null;
                if (mlConfigModel != null)
                {
                    mlCaseType = mlConfigModel.CaseTypes.FirstOrDefault(x => x.Value == caseType);

                }
                foreach (CaseCauseModel causeModel in caseCausesList)
                {
                    string ew_id = "";
                    string situationID = "";
                    string cc_id = causeModel.CC_ID;
                    List<CommonPlotorSituation> models = new List<CommonPlotorSituation>();
                    //执行拆句

                    var sentences = base.SentenceSplitting(paragraphValue, paragraphCode, circumsatanModel, moduleType, causeModel.CC_ID, false);
                    if (sentences != null && sentences.Any())
                    {
                        List<SentenceModel> regSentences = new List<SentenceModel>();
                        if (paragraphmodel.isml == "1")
                        {
                            Stopwatch swtext1 = new Stopwatch();
                            swtext1.Start();
                            base.dataContext.InteractiveShow?.LogShow("使用机器学习开始:" + JsonConvert.SerializeObject(sentences));
                            //通过机器学习匹配情形数据
                            List<CommonPlotorSituation> matchLearnModels = base.MatchListByMachLearn(mlCaseType, cc_id, sentences, 1, out regSentences);
                            if (matchLearnModels != null && matchLearnModels.Any())
                                models.AddRange(matchLearnModels);


                            swtext1.Stop();
                            base.dataContext.InteractiveShow?.LogShow("使用机器学习调用时长:" + swtext1.Elapsed.TotalMilliseconds.ToString("0"));
                        }
                        else
                        {
                            regSentences = sentences;
                        }
                        if (regSentences != null && regSentences.Any())
                        {
                            if (paragraphmodel.isml != "1")
                            {
                                CommElementRegexCode commElement = new CommElementRegexCode();
                                commElement.CaseType = base.dataContext.DataLayerAns.CaseType;
                                commElement.PargarphCode = paragraphCode.ToLower();
                                commElement.PargarphWhere = "=";
                                commElement.Purpose = ExtractType.plotorsituation;
                                commElement.SourceCode = docType;
                                bool isRuleitem = causeModel.CC_DevelopSchedule == 1 || causeModel.CC_DevelopSchedule == 2 ? true : false;
                                string match = isRuleitem ? "Regex" : "RuleItem";
                                base.dataContext.InteractiveShow?.LogShow($"通过正则进行情形提取：当前案由的匹配规则为：{match}");
                                if (regSentences.Any(x => x.SentenceType == "1"))
                                {
                                    string affirmContent = string.Join("", regSentences.Where(x => x.SentenceType == "1").Select(x => x.SentenceContent));
                                    var affirmModels = MatchValueID(cc_id, isRuleitem, affirmContent, commElement, "1", "", paragraphmodel.isml);
                                    if (affirmModels != null && affirmModels.Any())
                                        models.AddRange(affirmModels);
                                }
                                if (regSentences.Any(x => x.SentenceType == "0"))
                                {
                                    string unAffirmContent = string.Join("", regSentences.Where(x => x.SentenceType == "0").Select(x => x.SentenceContent));
                                    var unAffirmModels = MatchValueID(cc_id, isRuleitem, unAffirmContent, commElement, "0", "", paragraphmodel.isml);
                                    if (unAffirmModels != null && unAffirmModels.Any())
                                        models.AddRange(unAffirmModels);
                                }

                            }
                        }
                        if (models.Count > 0)
                        {
                            models = models.Where((x, i) => models.FindIndex(z => z.Common_id == x.Common_id) == i).ToList();
                        }
                        for (int i = 0; i < models.Count; i++)
                        {
                            foreach (string pid in models[i].Common_parentid)
                            {
                                var model = models.FirstOrDefault(a => a.Common_id == pid);
                                if (model != null)
                                {
                                    models.Remove(model);
                                }
                            }
                        }
                        #region 对匹配到的情形，作入库操作
                        List<string> idList = new List<string>();
                        //----------------------------------
                        //查询到的对应情形对象列表
                        foreach (var item in models)
                        {

                            Dictionary<string, string> row = new Dictionary<string, string>();
                            row.Add("rs_ismatch", "1");
                            row.Add("rs_matchsource", "0");
                            row.Add("rs_affirmidearesult", item.Common_affirm);
                            row.Add("ms_affirmideasource", "0");
                            row.Add("rs_situationname", item.Common_name);
                            row.Add("rs_statussource", paragraphmodel.Type);
                            row.Add("rs_situationid", item.Common_id);
                            row.Add("originaltext", item.Common_originalText);
                            idList.Add(item.Common_id);
                            row.Add("ew_id", "");
                            row.Add("CaseCause", causeModel.CC_ID);
                            rowsdic.Add(row);
                        }
                        if (idList.Count > 0)
                        {
                            SituationExpressAdd situationExpressAdd = new SituationExpressAdd();
                            situationID = situationExpressAdd.GetGroupSituationID("1", 1, "1", idList);
                            ///根据组合情节获取表述ID
                            ew_id = situationExpressAdd.GetGroupExpressID(situationID, dataContext.DataLayerAns.CaseType, true);
                        }
                        #endregion
                    }
                }

            }

            return rowsdic;
        }

        #region 注释代码
        /// <summary>
        /// 情形表数据做补充
        /// </summary>
        public void MatchSituationSupplement(List<DataModel> dataModelAsisModelList, string parid, string moduleType)
        {
            dicContent.Clear();
            //dicFJContent.Clear();
            if (base.dataContext.DataLayerAns.CaseCausesList == null || base.dataContext.DataLayerAns.CaseCausesList.Count == 0)
            {
                base.dataContext.InteractiveShow.LogShow(" 当前案由未获取到，不进行情形的分析！");
                return;
            }
            RuleParseClass.WriteContentLog(" *********************@开始情形提取****************************");

            base.dataContext.InteractiveShow.LogShow(" *********************@开始情形提取****************************");
            Stopwatch swtext = new Stopwatch();
            swtext.Start();

            string ew_id = "";
            string situationID = "";
            //是否机器学习
            bool isMatchLearn = false;
            SituationPlotMLCaseType mlCaseType = null;
            if (mlConfigModel != null)
            {
                mlCaseType = mlConfigModel.CaseTypes.FirstOrDefault(x => x.Value == dataContext.DataLayerAns.CaseType);
                if (mlCaseType != null)
                    isMatchLearn = true;
            }
            foreach (var causeModel in dataContext.DataLayerAns.CaseCausesList)
            {
                Stopwatch s1 = new Stopwatch();
                s1.Restart();
                List<Dictionary<string, string>> rowsdic = new List<Dictionary<string, string>>();
                Dictionary<string, List<ForeignKey>> extorgtext = ExtSituationContent(causeModel.CC_ID, "", dataModelAsisModelList, parid);
                //GroupBy(ke => ke.Item1).ToDictionary(a => a.Key, b => b.ToList());
                //var res= extorgtext["investigate"].GroupBy(x => x.Oringtext).ToDictionary(a => a.Key, b => b.ToList());
                base.dataContext.InteractiveShow.LogShow("匹配到的原文为:" + JsonConvert.SerializeObject(extorgtext));
                s1.Stop();
                RuleParseClass.WriteContentLog("解析配置信息完毕，耗时：" + s1.Elapsed.TotalMilliseconds.ToString("0") + "结果：" + JsonConvert.SerializeObject(extorgtext));
                string cc_id = causeModel.CC_ID;
                foreach (var dicorg in extorgtext)
                {
                    foreach (ForeignKey org in dicorg.Value)
                    {
                        s1.Restart();
                        List<CommonPlotorSituation> models = new List<CommonPlotorSituation>();
                        //执行拆句
                        var sentences = base.SentenceSplitting(org.Oringtext, org.paragraphCode, circumsatanModel, moduleType, causeModel.CC_ID, false);
                        s1.Stop();
                        RuleParseClass.WriteContentLog("进行拆句原文：" + org.Oringtext + "，耗时：" + s1.Elapsed.TotalMilliseconds.ToString("0") + "结果：" + JsonConvert.SerializeObject(sentences));

                        if (sentences != null && sentences.Any())
                        {
                            List<SentenceModel> regSentences = new List<SentenceModel>();
                            if (isMatchLearn == true && org.isml == "1")
                            {
                                Stopwatch swtext1 = new Stopwatch();
                                swtext1.Start();
                                base.dataContext.InteractiveShow.LogShow("使用机器学习开始:" + JsonConvert.SerializeObject(sentences));
                                //通过机器学习匹配情形数据
                                List<CommonPlotorSituation> matchLearnModels = base.MatchListByMachLearn(mlCaseType, cc_id, sentences, 1, out regSentences);
                                if (matchLearnModels != null && matchLearnModels.Any())
                                    models.AddRange(matchLearnModels);


                                swtext1.Stop();
                                base.dataContext.InteractiveShow.LogShow("使用机器学习调用时长:" + swtext1.Elapsed.TotalMilliseconds.ToString("0"));
                                RuleParseClass.WriteContentLog("拆句后使用机器学习调用时长：" + swtext1.Elapsed.TotalMilliseconds.ToString("0") + "原文：" + JsonConvert.SerializeObject(sentences));
                            }
                            else
                            {
                                regSentences = sentences;
                            }
                            if (regSentences != null && regSentences.Any())
                            {
                                if (org.isml != "1")
                                {
                                    CommElementRegexCode commElement = new CommElementRegexCode();
                                    commElement.CaseType = base.dataContext.DataLayerAns.CaseType;
                                    commElement.PargarphCode = org.paragraphCode.ToLower();
                                    commElement.PargarphWhere = "=";
                                    commElement.Purpose = ExtractType.plotorsituation;
                                    commElement.SourceCode = base.dataContext.DataLayerAns.SourceCode;
                                    bool isRuleitem = causeModel.CC_DevelopSchedule == 1 || causeModel.CC_DevelopSchedule == 2 ? true : false;
                                    string match = isRuleitem ? "Regex" : "RuleItem";
                                    base.dataContext.InteractiveShow.LogShow($"通过正则进行情形提取：当前案由的匹配规则为：{match}");
                                    if (regSentences.Any(x => x.SentenceType == "1"))
                                    {
                                        s1.Restart();
                                        string affirmContent = string.Join("", regSentences.Where(x => x.SentenceType == "1").Select(x => x.SentenceContent));
                                        //先进行整句的判断，如果整句已经匹配过则不进行重新匹配
                                        if (dicContent.ContainsKey(affirmContent))
                                        {
                                            models.AddRange(dicContent[affirmContent]);
                                        }
                                        else
                                        {
                                            //mo.Common_originalText.Trim(new char[] { '，', '。' })
                                            //判断分句里面 是否已经有匹配的，有则去掉已经匹配的
                                            //List<CommonPlotorSituation> regSentencesPp = new List<CommonPlotorSituation>();
                                            //if (dicFJContent.Count > 0)
                                            //{

                                            //    List<SentenceModel> regSentencesNew = new List<SentenceModel>();
                                            //    regSentences.ForEach(x =>
                                            //    {
                                            //        if (!dicFJContent.ContainsKey(x.SentenceContent.Trim(new char[] { '，', '。' })))
                                            //        {
                                            //            regSentencesNew.Add(x);
                                            //        }
                                            //        else
                                            //        {
                                            //            regSentencesPp.AddRange(dicFJContent[x.SentenceContent.Trim(new char[] { '，', '。' })]);
                                            //        }
                                            //    });
                                            //    affirmContent = string.Join("", regSentencesNew.Where(x => x.SentenceType == "1").Select(x => x.SentenceContent));
                                            //}
                                            var affirmModels = MatchValueID(cc_id, isRuleitem, affirmContent, commElement, "1", "", org.isml);
                                            if (affirmModels != null && affirmModels.Any())
                                                models.AddRange(affirmModels);
                                            //if (regSentencesPp.Any())
                                            //    models.AddRange(regSentencesPp);
                                            //string affirmContentNew = string.Join("", regSentences.Where(x => x.SentenceType == "1").Select(x => x.SentenceContent));

                                            if (!dicContent.ContainsKey(affirmContent))
                                            {
                                                dicContent.Add(affirmContent, models);
                                            }
                                            //sentences.ForEach(x =>
                                            //{
                                            //    if (!dicFJContent.ContainsKey(x.SentenceContent))
                                            //    {
                                            //        dicFJContent.Add(x.SentenceContent,new CommonPlotorSituation());
                                            //    }
                                            //});


                                            s1.Stop();
                                            RuleParseClass.WriteContentLog("进行认定句匹配原文：" + affirmContent + "，耗时：" + s1.Elapsed.TotalMilliseconds.ToString("0") + "结果：" + JsonConvert.SerializeObject(affirmModels));
                                        }

                                    }
                                    if (regSentences.Any(x => x.SentenceType == "0"))
                                    {
                                        s1.Restart();
                                        string unAffirmContent = string.Join("", regSentences.Where(x => x.SentenceType == "0").Select(x => x.SentenceContent));
                                        if (dicContent.ContainsKey(unAffirmContent))
                                        {
                                            models.AddRange(dicContent[unAffirmContent]);
                                        }
                                        else
                                        {
                                            //List<CommonPlotorSituation> regSentencesPp = new List<CommonPlotorSituation>();
                                            //if (dicFJContent.Count > 0)
                                            //{

                                            //    List<SentenceModel> regSentencesNew = new List<SentenceModel>();
                                            //    regSentences.ForEach(x =>
                                            //    {
                                            //        if (!dicFJContent.ContainsKey(x.SentenceContent.Trim(new char[] { '，', '。' })))
                                            //        {
                                            //            regSentencesNew.Add(x);
                                            //        }
                                            //        else
                                            //        {
                                            //            regSentencesPp.AddRange(dicFJContent[x.SentenceContent.Trim(new char[] { '，', '。' })]);
                                            //        }
                                            //    });
                                            //    unAffirmContent = string.Join("", regSentencesNew.Where(x => x.SentenceType == "0").Select(x => x.SentenceContent));
                                            //}
                                            var unAffirmModels = MatchValueID(cc_id, isRuleitem, unAffirmContent, commElement, "0", "", org.isml);
                                            if (unAffirmModels != null && unAffirmModels.Any())
                                                models.AddRange(unAffirmModels);
                                            //if (regSentencesPp.Any())
                                            //    models.AddRange(regSentencesPp);
                                            if (!dicContent.ContainsKey(unAffirmContent))
                                            {
                                                dicContent.Add(unAffirmContent, unAffirmModels);
                                            }
                                            //sentences.ForEach(x =>
                                            //{
                                            //    if (!dicFJContent.ContainsKey(x.SentenceContent))
                                            //    {
                                            //        dicFJContent.Add(x.SentenceContent, new CommonPlotorSituation());
                                            //    }
                                            //});

                                            s1.Stop();
                                            RuleParseClass.WriteContentLog("进行否定句匹配原文：" + unAffirmContent + "，耗时：" + s1.Elapsed.TotalMilliseconds.ToString("0") + "结果：" + JsonConvert.SerializeObject(unAffirmModels));
                                        }
                                    }

                                }
                            }
                            s1.Restart();
                            if (models.Count > 0)
                            {
                                models = models.Where((x, i) => models.FindIndex(z => z.Common_id == x.Common_id) == i).ToList();
                            }
                            for (int i = 0; i < models.Count; i++)
                            {
                                foreach (string pid in models[i].Common_parentid)
                                {
                                    var model = models.FirstOrDefault(a => a.Common_id == pid);
                                    if (model != null)
                                    {
                                        models.Remove(model);
                                    }
                                }
                            }
                            RuleParseClass.WriteContentLog("匹配到的情形数量" + models.Count);
                            #region 对匹配到的情形，作入库操作
                            List<string> idList = new List<string>();
                            //----------------------------------
                            //查询到的对应情形对象列表
                            foreach (var item in models)
                            {
                                var rowsituationtemp = rowsdic.FirstOrDefault(rowsituation => LdFormat.GetDicValue(rowsituation, "rs_situationid") == item.Common_id && LdFormat.GetDicValue(rowsituation, "rs_statussource") == dicorg.Key && LdFormat.GetDicValue(rowsituation, "rs_id") == org.Fk);
                                if (rowsituationtemp==null)
                                {
                                    Dictionary<string, string> row = new Dictionary<string, string>();
                                    row.Add("rs_id", org.Fk);
                                    row.Add("rs_ismatch", "1");
                                    row.Add("rs_matchsource", "0");
                                    row.Add("rs_affirmidearesult", item.Common_affirm);
                                    row.Add("ms_affirmideasource", "0");
                                    row.Add("rs_situationname", item.Common_name);
                                    row.Add("rs_statussource", dicorg.Key);
                                    row.Add("rs_situationid", item.Common_id);
                                    row.Add("originaltext", item.Common_originalText);
                                    if (dicorg.Key == "convicted")
                                    {
                                        row.Add("msp_id", org.Fk); //量刑单罪ID
                                    }
                                    else
                                    {
                                        row.Add("lt_id", org.Fk);    //指控ID 
                                    }
                                    row.Add("path", org.Path);
                                    idList.Add(item.Common_id);
                                    row.Add("ew_id", "");
                                    rowsdic.Add(row);
                                }
                            }
                            if (idList.Count > 0)
                            {
                                SituationExpressAdd situationExpressAdd = new SituationExpressAdd();
                                situationID = situationExpressAdd.GetGroupSituationID("1", 1, "1", idList);
                                ///根据组合情节获取表述ID
                                ew_id = situationExpressAdd.GetGroupExpressID(situationID, dataContext.DataLayerAns.CaseType, true);
                            }
                            #endregion
                            s1.Stop();
                            RuleParseClass.WriteContentLog("根据查询到的对应情形对象列表获取ewid：" + ew_id + "，耗时：" + s1.Elapsed.TotalMilliseconds.ToString("0"));

                        }
                    }
                }
                s1.Restart();
                DataSaveSituation_new(rowsdic, ew_id, situationID, dataModelAsisModelList, parid);
                s1.Stop();
                RuleParseClass.WriteContentLog("执行数据保存耗时：" + s1.Elapsed.TotalMilliseconds.ToString("0"));

            }

            swtext.Stop();
            base.dataContext.InteractiveShow.LogShow(" *********************@情形提取结束耗时：" + swtext.Elapsed.TotalMilliseconds.ToString("0") + "****************************");
            RuleParseClass.WriteContentLog(" *********************@情形提取结束耗时：" + swtext.Elapsed.TotalMilliseconds.ToString("0") + "****************************");

        }

        /// <summary>
        /// 数据保存
        /// </summary>
        /// <param name="DataModelDic">数据集合</param>
        /// <param name="ew_id">组合表述</param>
        public void DataSaveSituation_new(List<Dictionary<string, string>> DataModelDic, string ew_id, string situationID, List<DataModel> dataModelAsisModelList, string parid)
        {
            DataSoursModel dataSoursModel = new DataSoursModel();
            dataSoursModel.dataModelList = dataModelAsisModelList;
            foreach (Dictionary<string, string> dicValue in DataModelDic)
            {
                string path = dicValue["rs_id"];
                DataModel dataModelParent = dataSoursModel.dataModelList.FirstOrDefault(a => a.ID == path);
                if (dataModelParent == null)
                {
                    CaseNodeUpdate(dataSoursModel.dataModelList, path);
                    dataModelParent = dataSoursModel.dataModelList.FirstOrDefault(a => a.XmlPath == path);
                    DataSaveAtticeton(dataModelParent, dicValue);
                }
                else
                {
                    DataModel dataModel = new DataModel();
                    dataModel.XmlPath = dataModelParent.XmlPath + "/详情";
                    dataModel.ParentId = dataModelParent.ID;
                    dataModel.sourceData = new SourceData();
                    dataModel.ID = Snowflake.Instance().GetId().ToString();
                    Source source = new Source();
                    source.SourceCode = dataContext.DataLayerAns.SourceCode;
                    source.IsCheck = "1";
                    dataModel.sourceData.sourceList = new List<Source>();
                    dataModel.sourceData.sourceList.Add(source);

                    DataSaveAtticeton(dataModel, dicValue);
                    dataSoursModel.dataModelList.Add(dataModel);
                    var originaltext = dicValue["originaltext"];
                    if (!string.IsNullOrWhiteSpace(originaltext))
                    {
                        DataModel originalDataModel = new DataModel();
                        originalDataModel.XmlPath = dataModelParent.XmlPath + "/详情/原文";
                        originalDataModel.ParentId = dataModel.ID;
                        originalDataModel.sourceData = new SourceData();
                        originalDataModel.ID = Snowflake.Instance().GetId().ToString();
                        Source originalSource = new Source();
                        originalSource.SourceCode = dataContext.DataLayerAns.SourceCode;
                        originalSource.IsCheck = "1";
                        originalDataModel.sourceData.sourceList = new List<Source>();
                        originalDataModel.sourceData.sourceList.Add(originalSource);
                        originalDataModel.AttributesList = new List<AttributeInfo>();
                        SetAttion("原文", originaltext, originalDataModel);
                        dataSoursModel.dataModelList.Add(originalDataModel);
                    }


                }

                if (dataModelParent != null)
                {
                    if (dataModelParent.AttributesList.Count > 0)
                    {
                        if (dataModelParent.AttributesList.FirstOrDefault(a => a.Name == "组合表述ID") != null)
                            dataModelParent.AttributesList.FirstOrDefault(a => a.Name == "组合表述ID").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue = ew_id;
                        else
                            SetAttion("组合表述ID", ew_id, dataModelParent);

                        if (dataModelParent.AttributesList.FirstOrDefault(a => a.Name == "组合情形ID") != null)
                            dataModelParent.AttributesList.FirstOrDefault(a => a.Name == "组合情形ID").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue = situationID;
                        else
                            SetAttion("组合情形ID", situationID, dataModelParent);
                    }
                    else
                    {
                        SetAttion("组合表述ID", ew_id, dataModelParent);
                        SetAttion("组合情形ID", situationID, dataModelParent);
                    }
                }
            }
            //dataContext.DataLayerAns.AnalysisResultsDataModel = dataSoursModel;
            //XmlDocument xmlDocumentp = XmlUtility.DataModelByXml(dataSoursModel.dataModelList);
            //dataContext.DataLayerAns.AnalysisResultsXml = xmlDocumentp;
        }



        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="dataModel"></param>
        public void DataSaveAtticeton(DataModel dataModel, Dictionary<string, string> DicValue)
        {
            dataModel.AttributesList = new List<AttributeInfo>();
            SetAttion("情形ID", DicValue["rs_situationid"], dataModel);
            SetAttion("情形名称", DicValue["rs_situationname"], dataModel);
            SetAttion("情形来源", DicValue["rs_statussource"], dataModel);
            SetAttion("情形认定意见结果", DicValue["rs_affirmidearesult"], dataModel);
            SetAttion("组合表述ID", DicValue["ew_id"], dataModel);
            //SetAttion("原文", DicValue["originaltext"], dataModel);
        }

        public void SetAttion(string attributeName, string attributeValue, DataModel dataModel)
        {
            AttributeInfo attribute = new AttributeInfo();
            attribute.Name = attributeName;
            attribute.sourceList = new List<Source>();
            Source source = new Source();
            source.SaveValue = attributeValue;
            source.SourceCode = dataContext.DataLayerAns.SourceCode;
            source.IsCheck = "1";
            attribute.sourceList.Add(source);
            dataModel.AttributesList.Add(attribute);

        }
        /// <summary>
        /// 解析配置信息
        /// </summary>
        /// <param name="tbl_id"></param>
        /// <param name="xmldoc"></param>
        /// <param name="dataModelAnalysisList"></param>
        /// <param name="parid"></param>
        /// <param name="sentenceReg">拆句正则</param>
        /// <param name="denyReg">判断否定语句正则</param>
        /// <returns></returns>
        private Dictionary<string, List<ForeignKey>> ExtSituationContent(string tbl_id, string xmldoc, List<DataModel> dataModelAnalysisList, string parid)
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
            Dictionary<string, List<ForeignKey>> orgtext = new Dictionary<string, List<ForeignKey>>();
            List<ParagraphModel> paragraphlList = new List<ParagraphModel>();
            if (paragraphModelList.Count == 0 && circumsatanModel != null && circumsatanModel.casetypeModelList.Count > 0)
            {
                CasetypeModel casetypeModel = circumsatanModel.casetypeModelList.FirstOrDefault(a => a.Code.ToLower() == dataContext.DataLayerAns.CaseType.ToLower());
                if (casetypeModel != null)
                {
                    var doctypeModel = casetypeModel.docTypeList.FirstOrDefault(x => x.Code.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower());
                    if (doctypeModel != null)
                    {
                        List<ParagraphModel> modelList = new List<ParagraphModel>();
                        paragraphlList = casetypeModel.docTypeList.FirstOrDefault(a => a.Code.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower()).paragraphModelList;
                        List<ParagraphModel> paragraphCauseList = paragraphlList.Where(a => a.causecode == tbl_id).ToList();
                        List<ParagraphModel> paragraphCauseNotList = paragraphlList.Where(a => a.causecode == null || a.causecode == "").ToList();
                        if (paragraphCauseList == null || paragraphCauseList.Count == 0)
                        {
                            modelList = paragraphCauseNotList;
                        }
                        else if (paragraphCauseList.Count > 0)
                        {
                            if (modelList.Count == 0)
                            {
                                modelList = paragraphCauseList;
                            }
                            else
                            {
                                foreach (var model in paragraphCauseNotList)
                                {
                                    if (modelList.FirstOrDefault(a => a.Code == model.Code) == null)
                                    {
                                        modelList.Add(model);
                                    }
                                }
                            }
                        }

                        foreach (var paragraphValue in modelList)
                        {
                            foreach (var pathvlaue in paragraphValue.pathModelList)
                            {
                                if (pathvlaue.Type == "1")
                                {

                                    string xpath = pathvlaue.value.Replace("{causecode}", tbl_id);
                                    foreach (DataModel dataModel in XmlUtility.ConditionDataModelList(dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList, "", xpath))
                                    {
                                        ForeignKey key = new ForeignKey();
                                        key.Oringtext = dataModel.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                                        key.Fk = dataModel.ID;
                                        key.Path = paragraphValue.pathModelList.FirstOrDefault(a => a.Type == "1").value;
                                        key.paragraphCode = paragraphValue.Code;
                                        if (paragraphValue.causecode == tbl_id)
                                        {
                                            key.isml = paragraphValue.isml;
                                        }

                                        if (orgtext.ContainsKey(paragraphValue.Type))
                                        {
                                            orgtext[paragraphValue.Type].Add(key);
                                        }
                                        else
                                        {
                                            List<ForeignKey> Keylist = new List<ForeignKey>();
                                            Keylist.Add(key);
                                            orgtext.Add(paragraphValue.Type, Keylist);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else if (paragraphModelList != null)
            {
                List<ParagraphModel> modelList = new List<ParagraphModel>();
                paragraphlList = paragraphModelList;
                List<ParagraphModel> paragraphCauseList = paragraphlList.Where(a => a.causecode == tbl_id).ToList();
                List<ParagraphModel> paragraphCauseNotList = paragraphlList.Where(a => a.causecode == null || a.causecode == "").ToList();
                if (paragraphCauseList == null || paragraphCauseList.Count == 0)
                {
                    modelList = paragraphCauseNotList;
                }
                else if (paragraphCauseList.Count > 0)
                {
                    if (modelList.Count == 0)
                    {
                        modelList = paragraphCauseList;
                    }
                    else
                    {
                        foreach (var model in paragraphCauseNotList)
                        {
                            if (modelList.FirstOrDefault(a => a.Code == model.Code) == null)
                            {
                                modelList.Add(model);
                            }
                        }
                    }
                }
                foreach (var paragraphValue in modelList)
                {
                    foreach (var pathvlaue in paragraphValue.pathModelList)
                    {
                        if (pathvlaue.Type == "1")
                        {
                            List<string> valueList = pathvlaue.value.Split(new string[] { "事实要素" }, System.StringSplitOptions.None).ToList();

                            string pathvalue = "";
                            if (valueList.Count > 0)
                            {
                                pathvalue = valueList[0] + "事实要素";
                                pathvalue = pathvalue.Replace("{causecode}", tbl_id);
                            }

                            string xpath = pathvlaue.value.Replace("{causecode}", tbl_id);
                            foreach (DataModel dataModel in XmlUtility.ConditionDataModelList(dataModelAnalysisList, parid, xpath))
                            {
                                string suitid = "";
                                List<DataModel> dataModeElmentlList = xmlUtilCommon.SubParentDateModel(dataModelAnalysisList, dataModel);
                                DataModel dataModelRoot = XmlUtility.ConditionFirstOrDefaultDataModel(dataModeElmentlList, "", pathvalue);
                                if (dataModelRoot != null)
                                {
                                    if (dataModelAnalysisList.FirstOrDefault(a => a.ParentId == dataModelRoot.ID) != null)
                                    {
                                        DataModel dataModelRootzfg = dataModelAnalysisList.FirstOrDefault(a => a.ParentId == dataModelRoot.ID && a.XmlPath.IndexOf("主张方") > -1);
                                        if (dataModelRootzfg != null)
                                        {
                                            string id = dataModelRootzfg.AttributesList.FirstOrDefault(a => a.Name == "主张方诉讼地位").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                                            if (id == "306")
                                            {
                                                suitid = "investigate";
                                            }
                                            else if (id == "164")
                                            {
                                                suitid = "legation";
                                            }
                                            else if (id == "1")
                                            {
                                                suitid = "defense";
                                            }
                                        }
                                    }
                                }
                                ForeignKey key = new ForeignKey();
                                key.Oringtext = HttpHelp.DeCodeBase64new(65001, dataModel.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1").OriginalText);
                                key.Fk = dataModel.ID;
                                key.Path = paragraphValue.pathModelList.FirstOrDefault(a => a.Type == "1").value;
                                key.paragraphCode = paragraphValue.Code;
                                if (paragraphValue.causecode == tbl_id)
                                {
                                    key.isml = paragraphValue.isml;
                                }
                                if (orgtext.ContainsKey(suitid))
                                {
                                    orgtext[suitid].Add(key);
                                }
                                else
                                {
                                    List<ForeignKey> Keylist = new List<ForeignKey>();
                                    Keylist.Add(key);
                                    orgtext.Add(suitid, Keylist);
                                }
                            }
                        }
                    }
                }
            }
            return orgtext;
        }
        #endregion

    }
}
